<?php

namespace app\admin\model\workteam;

use app\admin\library\Auth;
use think\Model;
use think\Loader;

class Accountlog extends Model
{

    // 表名
    protected $name = 'workteam_accountlog';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = '';
    private $w_config = [];

    protected static function init()
    {
        //支出时间数据格式处理
        self::event('before_insert', function ($row) {
            !is_numeric($row['pay_time']) ? $row['pay_time'] = strtotime($row['pay_time']) : '';
        });
        self::event('before_update', function ($row) {
            $changedData = $row->getChangedData();
            //支出时间数据格式处理
            isset($changedData['pay_time']) && !is_numeric($changedData['pay_time']) ? $changedData['pay_time'] = strtotime($changedData['pay_time']) : '';
        });
    }


    public function getTypeList()
    {
        if (!$this->w_config) {
            $this->w_config = get_addon_config('workteam');
        }
        return isset($this->w_config['accounttype']) ? $this->w_config['accounttype'] : [];

    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['type'];
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 关联项目
     */
    public function project()
    {
        return $this->belongsTo("\app\admin\model\workteam\Project", 'project_id');
    }

    /**
     * 支出类型统计
     * @param $startDate
     * @param $endDate
     * @param null $project_ids
     * @return bool|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getLogTypeEchart($startDate = null, $endDate = null, $project_ids = null)
    {
        if ($startDate) {
            // 生成查询的开始和结束时间，默认取30日
            !is_numeric($startDate) && $starttime = strtotime($startDate);
            !is_numeric($endDate) && $endtime = strtotime($endDate);
            $isnotrangeDate = empty($starttime) && empty($endtime);
            $nearly = '30';
            if ($isnotrangeDate) {
                $endtime = time();
                $nearly -= 1;
                $starttime = strtotime("-{$nearly} day");  // 最近30天日期
            } elseif ($starttime > $endtime) {
                $this->error = '起始时间要小于终止时间';
                return false;
            }
            $this->where('pay_time', 'between time', [$starttime, $endtime]);
        }

        $tempwhere = array();
        if ($project_ids && is_numeric($project_ids)) {
            $tempwhere['project_id'] = $project_ids;
        } elseif ($project_ids && is_array($project_ids)) {
            $tempwhere['project_id'] = ['in', $project_ids];

        }
        $lists = $this->where($tempwhere)->field('COUNT(*) AS nums, sum(money) as money,type')->group('type')->select();
        return $lists;


    }


    /**
     * 支出统计
     * @param $startDate
     * @param $endDate
     * @param null $project_ids 项目IDs
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getLogEchart($startDate = null, $endDate = null, $project_ids = null)
    {

        // 生成查询的开始和结束时间，默认取30日
        !is_numeric($startDate) && $starttime = strtotime($startDate);
        !is_numeric($endDate) && $endtime = strtotime($endDate);
        $isnotrangeDate = empty($starttime) && empty($endtime);
        $nearly = '30';
        if ($isnotrangeDate) {
            $endtime = time();
            $nearly -= 1;
            $starttime = strtotime("-{$nearly} day");  // 最近30天日期
        } elseif ($starttime > $endtime) {
            $this->error = '起始时间要小于终止时间';
            return false;
        }
        $totalseconds = $endtime - $starttime;;
        if ($totalseconds > 86400 * 30 * 2) {
            $format = '%Y-%m';
        } else {
            if ($totalseconds > 86400) {
                $format = '%Y-%m-%d';
            } else {
                $format = '%H:00';
            }
        }
        $tempwhere = array();
        if ($project_ids && is_numeric($project_ids)) {
            $tempwhere['project_id'] = $project_ids;
        } elseif ($project_ids && is_array($project_ids)) {
            $tempwhere['project_id'] = ['in', $project_ids];
        }elseif($project_ids==0){
            $tempwhere['project_id'] = $project_ids;
        }
        $lists = $this->where($tempwhere)->where('pay_time', 'between time', [$starttime, $endtime])
            ->field('COUNT(*) AS nums, sum(money) as expenses, DATE_FORMAT(FROM_UNIXTIME(pay_time), "' . $format . '") AS add_date')
            ->group('add_date')
            ->select();


        if ($totalseconds > 84600 * 30 * 2) {
            $starttime = strtotime('last month', $starttime);
            while (($starttime = strtotime('next month', $starttime)) <= $endtime) {
                $column[] = date('Y-m', $starttime);
            }
        } else {
            if ($totalseconds > 86400) {
                for ($time = $starttime; $time <= $endtime;) {
                    $column[] = date("Y-m-d", $time);
                    $time += 86400;
                }
            } else {
                for ($time = $starttime; $time <= $endtime;) {
                    $column[] = date("H:00", $time);
                    $time += 3600;
                }
            }
        }


        $c_count = $c_price = $c_expenses = array_fill_keys($column, 0);

        foreach ($lists as $k => $v) {
            $c_count[$v['add_date']] = $v['nums'];//支出笔数
            $c_expenses[$v['add_date']] = $v['expenses'];//支出金额
        }


        $data = [
            'date' => array_keys($c_count),
            'data' => [
                __("支出笔数") => array_values($c_count),
                __("支出金额") => array_values($c_expenses),

            ],
        ];
        return $data;
    }


}
